import { ChangeDetectionStrategy, Component, Input, OnChanges, SimpleChanges, ViewEncapsulation } from '@angular/core';
import { TypeUtils } from '../core/api';

@Component({
  selector: 'lv-highlight',
  templateUrl: './highlight.component.html',
  encapsulation: ViewEncapsulation.None,
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class HighlightComponent implements OnChanges {
  @Input() lvContent: string = ''; // 适配number场景
  @Input() lvWholeStr: string = '';

  nodeList: Array<{ className?: string; content: string }> = [];

  ngOnChanges(changes: SimpleChanges): void {
    if (changes.lvContent) {
      this.getHighlightStr();
    }
  }

  getHighlightStr(): void {
    this.nodeList = [];
    if (!TypeUtils.isRealString(this.lvContent) || !this.lvContent) {
      return;
    }
    let keyword = this.lvContent.trim();
    if (keyword === '') {
      return;
    }
    const space = keyword.length;
    keyword = keyword.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');

    // 根据业务方需求，后续是否添加大小写区分
    const highlightClass = 'lv-highlight-keyword';
    const reg = new RegExp(keyword, 'ig');
    const str = this.lvWholeStr;
    let result = reg.exec(str);
    let i = 0;
    while (result) {
      this.nodeList.push({ content: str.slice(i, result.index) });
      this.nodeList.push({ content: result[0], className: highlightClass });
      i = result.index + space;
      result = reg.exec(str);
    }
    this.nodeList.push({ content: str.slice(i) });
  }
}
